package cn.walls1717.ggkt.vod.service.impl;

import cn.walls1717.ggkt.model.vod.Chapter;
import cn.walls1717.ggkt.model.vod.Video;
import cn.walls1717.ggkt.vo.vod.ChapterVo;
import cn.walls1717.ggkt.vo.vod.VideoVo;
import cn.walls1717.ggkt.vod.mapper.ChapterMapper;
import cn.walls1717.ggkt.vod.service.ChapterService;
import cn.walls1717.ggkt.vod.service.VideoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 课程章节服务实现类
 *
 * @author walls1717
 * @since 2022/07/14
 */
@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements ChapterService {

    @Autowired
    private VideoService videoService;

    /**
     * 大纲列表
     */
    @Override
    public List<ChapterVo> listTree(Long courseId) {
        // 根据课程id获取到课程章节信息
        LambdaQueryWrapper<Chapter> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Chapter::getCourseId, courseId);
        List<Chapter> chapterList = this.list(lqw);

        // 根据课程id获取到课程视频信息
        LambdaQueryWrapper<Video> videoLqw = new LambdaQueryWrapper<>();
        videoLqw.eq(Video::getCourseId, courseId);
        List<Video> videoList = videoService.list(videoLqw);

        // 将chapter与video封装为chapterVo对象
        return chapterList.stream().map(item->{
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(item, chapterVo);
            // 将video对象封装为videoVo对象
            List<VideoVo> videoVoList = videoList.stream().map(item2->{
                VideoVo videoVo = new VideoVo();
                BeanUtils.copyProperties(item2, videoVo);
                return videoVo;
            }).collect(Collectors.toList());
            // 设置子章节
            chapterVo.setChildren(videoVoList);
            return chapterVo;
        }).collect(Collectors.toList());
    }

    /**
     * 根据课程id删除
     */
    @Override
    public void removeByCourseId(Long id) {
        LambdaQueryWrapper<Chapter> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Chapter::getCourseId, id);
        this.remove(lqw);
    }
}
